<?php

class Util
{
	private static $_msgs = null;

	public static function generateToken()
	{
		return md5(uniqid(mt_rand()));
	}
	public static function encodePassword($password)
	{
		return md5($password.PASSWORD_SALT);
	}
	
	/**
	 * Returns the JSON representation of a value
	 * 
	 * @param  $value The value being encoded
	 * @return the JSON representation of a value
	 */
	public static function getJsonData($value)
	{
		$json = json_encode($value);
		//
		return $json;
		// 
		return preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $json);
	}
	/**
	 * Get the message by message code.
	 * 
	 * @param  $errorCode The Message Code
	 * @return String the message
	 */
	public static function getMessage($errorCode, $param = array())
	{
		if (null == self::$_msgs)
		{
			// Get the app config
	        $dir = Q::ini("app_config");
            self::$_msgs = parse_ini_file($dir['APP_DIR']."/config/message.ini");
		}
		if (array_key_exists($errorCode, self::$_msgs))
		{
			$msg = self::$_msgs[$errorCode];
			if (is_string($param))
			{
				$msg = str_replace('{0}', $param, $msg);
			}
			else
			{
				foreach($param as $i => $value)
				{
					$msg = str_replace('{'.$i.'}', $value, $msg);
				}
			}
			return $msg;
		}
		else
		{
		    return "";
		}
	}
	
	/**
     * Format the datetime
     * 
     * @param  String  $info 
     * @return String|Array the user info
     */
	public static function df($datetime, $formatStr = 'Y.m.d')
	{
		if (empty($datetime)) 
		{
			return "";
		}
		else
		{
		  return date($formatStr, $datetime);
		}
	}

    /**
     * Get the client ip address
     * 
     * @param  void
     * @return String    the client ip address
     */
	public static function getClientIp()
	{
		return @$_SERVER['HTTP_X_FORWARDED_FOR'];
		
		/*$ip = "";
		if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
		    $ip = $_SERVER['HTTP_CLIENT_IP'];
		}else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}else{
		    $ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;*/
	}
    
	public static function generateEmail($template, $param)
	{
		$email = array();
		$subject = $template['subject'];
		$content = $template['content'];
		foreach ($param as $k => $v)
		{
			$subject = str_replace('{$'.$k.'$}', $v, $subject);
			$content = str_replace('{$'.$k.'$}', $v, $content);
		}
		$email['subject'] = $subject;
		$email['content'] = $content;
		$email['sender'] = $template['sender'];
		return $email;
	}
	public static function HTTPStatus($num)
	{
		$http = array (
			100 => "HTTP/1.1 100 Continue",
			101 => "HTTP/1.1 101 Switching Protocols",
			200 => "HTTP/1.1 200 OK",
			201 => "HTTP/1.1 201 Created",
			202 => "HTTP/1.1 202 Accepted",
			203 => "HTTP/1.1 203 Non-Authoritative Information",
			204 => "HTTP/1.1 204 No Content",
			205 => "HTTP/1.1 205 Reset Content",
			206 => "HTTP/1.1 206 Partial Content",
			300 => "HTTP/1.1 300 Multiple Choices",
			301 => "HTTP/1.1 301 Moved Permanently",
			302 => "HTTP/1.1 302 Found",
			303 => "HTTP/1.1 303 See Other",
			304 => "HTTP/1.1 304 Not Modified",
			305 => "HTTP/1.1 305 Use Proxy",
			307 => "HTTP/1.1 307 Temporary Redirect",
			400 => "HTTP/1.1 400 Bad Request",
			401 => "HTTP/1.1 401 Unauthorized",
			402 => "HTTP/1.1 402 Payment Required",
			403 => "HTTP/1.1 403 Forbidden",
			404 => "HTTP/1.1 404 Not Found",
			405 => "HTTP/1.1 405 Method Not Allowed",
			406 => "HTTP/1.1 406 Not Acceptable",
			407 => "HTTP/1.1 407 Proxy Authentication Required",
			408 => "HTTP/1.1 408 Request Time-out",
			409 => "HTTP/1.1 409 Conflict",
			410 => "HTTP/1.1 410 Gone",
			411 => "HTTP/1.1 411 Length Required",
			412 => "HTTP/1.1 412 Precondition Failed",
			413 => "HTTP/1.1 413 Request Entity Too Large",
			414 => "HTTP/1.1 414 Request-URI Too Large",
			415 => "HTTP/1.1 415 Unsupported Media Type",
			416 => "HTTP/1.1 416 Requested range not satisfiable",
			417 => "HTTP/1.1 417 Expectation Failed",
			500 => "HTTP/1.1 500 Internal Server Error",
			501 => "HTTP/1.1 501 Not Implemented",
			502 => "HTTP/1.1 502 Bad Gateway",
			503 => "HTTP/1.1 503 Service Unavailable",
			504 => "HTTP/1.1 504 Gateway Time-out"
		);
		return $http[$num];
	}
	
	public static function getTimeElapsed($time){
		$current = time();
		$elapsed = $current - $time;
		if($elapsed < 0){
			return 'Invalid time';
		}elseif ($elapsed < 60 ){
			return "$elapsed seconds ago";
		}elseif ($elapsed < (60*60)){
			return round($elapsed/60) . ' minutes ago';
		}elseif ($elapsed < (60*60*24)){
			return round($elapsed/(60*60)) . ' hours ago';
		}else{
			return round($elapsed/(60*60*24)) . ' days ago';
		}
	}
	public static function getResult($n)
	{
		switch ($n)
		{
			case DOLLAR_20:
				return "Won $20";
			case DOLLAR_3:
				return "Won $3";
			case DOLLAR_1:
				return "Won $1";
			case CENT_50:
				return "Won $0.5";
			case CENT_10:
				return "Won $0.1";
			case CENT_5:
				return "Won $0.05";
			case CREDIT_20:
				return "20 Credits";
			case CREDIT_5:
				return "5 Credits";
			case CREDIT_1:
				return "1 Credit";
			default:
				return "Lose";
		}
	}
	
	public static function getGame($id)
	{
		if ($id == 1)
			return 'SLOT';
		if ($id == 2)
			return 'WHEEL';
		if ($id == 3)
			return 'POKER';
		return '';
	}
	
	private static function translateTemplate($content, $args){
		foreach ($args as $k => $v){
			$content = str_replace('[[' . $k . ']]', $v, $content);
		}
		return $content;
	}
	
	private static function getEmailSubject($tag, $site_template, $args){
		$config = Q::ini('templates_root').'/'.$site_template . '/email/email.ini';
		$subjects = parse_ini_file($config);
		$subject = isset($subjects[$tag]) ? $subjects[$tag] :false;
		if($subject){
			return self::translateTemplate($subject, $args);
		}
		return false;
	}

	public static function getRandonPassword($length = 6){
		$password = array();
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	    $count = strlen($chars);
	
	    for ($i = 0, $result = ''; $i < $length; $i++) {
	        $index = rand(0, $count - 1);
	        $result .= substr($chars, $index, 1);
	    }
	    
	 	$password[] = $result;
	 	$password[] = self::encodePassword($result);
	    return $password;
	}
	
	public static function getFrameTime($time)
	{
		return $time-$time%3600;
	}
	
	public static function getFormattedUserId($offerName, $userId, $siteDomain)
	{
		$uid = 0;
		$siteDomain = strtolower($siteDomain);
		switch ($offerName) {
			case 'PeanutLabs':
				if ($siteDomain == 'lalaloot.com') {
					$uid = $userId.'-4684-'.substr(md5($userId.'4684'.'7a023e4a695dd2735bdd3d407b575fea'), 0, 10);
				} elseif ($siteDomain == 'cashdazzle.com') {
					$uid = $userId.'-4676-'.substr(md5($userId.'4676'.'f211973200aed87ef558d3ec364765dc'), 0, 10);
				} else {
					$uid = $userId.'-4712-'.substr(md5($userId.'4712'.'e3d24dc5754aa85b269054f688423a52'), 0, 10);
				}
				break;
			case 'RadiumOne':
			case 'SuperRewards':
				$uid = $userId;
				break;
			default:
				$uid = 0;
		}
		return $uid;
	}
	
	public static function getParamsOfLinkUrl($offerName, $sendFrom = 'email') {
		$params = '';
		switch ($offerName) {
			case 'PeanutLabs':
				if($sendFrom == 'bluebar'){
					$params = '&var_key_2=bluebarid&var_val_2=[[bluebar_id]]';
				}else{
					$params = '&var_key_2=em&var_val_2=[[email_id]]';
				}
				break;
			case 'SuperRewards':
				if($sendFrom == 'bluebar'){
					$params = '&custom_bluebar=[[bluebar_id]]';
				}else{
					$params = '&custom_em=[[email_id]]';
				}
				break;
			case 'RadiumOne':
				if($sendFrom == 'bluebar'){
					$params = '&trackId=bluebarid_[[bluebar_id]]';
				}else{
					$params = '&trackId=[[email_id]]';
				}
				break;
			default:
				$params = '';
		}
		return $params;
	}
	
	public static function parseUkPostcode($postcode) {
	    $postcode = strtoupper(ereg_replace("[^A-Za-z0-9]", "", trim($postcode)));
	    $lenght = strlen($postcode);
     
    	if($lenght < 5 OR $lenght == 4){
    		$regex = '/^([A-Z]{1,2})([0-9][0-9A-Z]?)$/';
     
    		if (preg_match($regex, $postcode, $part)) {
			    $code = array(
			    'full' => $part[1] . $part[2],
			    'area' => $part[1],
			    'district' => $part[2],
			    'outer' => $part[1] . $part[2],
			    'sector' => NULL,
			    'walk' => NULL,
			    'inner' => NULL
			    );
    		}else{
     			$code = NULL;
	     	}
    	}else{
    		$regex = '/^([A-Z]{1,2})([0-9][0-9A-Z]?)\s*([0-9])([A-Z]{2})$/';
		    if (preg_match($regex, $postcode, $part)) {
			    $code = array(
			    'full' => $part[1].$part[2].' '.$part[3].$part[4],
			    'area' => $part[1],
			    'district' => $part[2],
			    'outer' => $part[1] . $part[2],
			    'sector' => $part[3],
			    'walk' => $part[4],
			    'inner' => $part[3] . $part[4]
			    );
		    }else{
		   		$code = NULL;
		    }
    	}
    	return $code;
    }
    
	public static function checkUKTelephone(&$strTelephoneNumber, &$intError, &$strError, $stripped = false) {
	  	// Copy the parameter and strip out the spaces
	  	$strTelephoneNumberCopy = str_replace (' ', '', $strTelephoneNumber);
	
	  	// Convert into a string and check that we were provided with something
	  	if (empty($strTelephoneNumberCopy)) {
	    	$intError = 1;
	    	$strError = 'Telephone number not provided';
	    	return false;
	  	}
	  
	  	// Don't allow country codes to be included (assumes a leading "+") 
	  	if (preg_match('/^(\+)[\s]*(.*)$/',$strTelephoneNumberCopy)) {
	    	$intError = 2;
	    	$strError = 'UK telephone number without the country code, please';
	    	return false;
	  	}
	  
	  	// Remove hyphens - they are not part of a telephone number
	 	$strTelephoneNumberCopy = str_replace ('-', '', $strTelephoneNumberCopy);
	  
	  	// Now check that all the characters are digits
	  	if (!preg_match('/^[0-9]{10,12}$/',$strTelephoneNumberCopy)) {
	    	$intError = 3;
	    	$strError = 'UK telephone numbers should contain 10 or 11 digits except the leading zero';
	    	return false;
	  	}
	  
	  	// Now check that the first digit is 0
	  	if (!preg_match('/^0[0-9]{9,11}$/',$strTelephoneNumberCopy)) {
	    	$intError = 4;
	    	$strError = 'The telephone number should start with a 0';
			return false;
	  	}		
	  
	  	// Check the string against the numbers allocated for dramas
	  
	  	// Expression for numbers allocated to dramas
		
		$tnexp[0] =  '/^(0113|0114|0115|0116|0117|0118|0121|0131|0141|0151|0161)(4960)[0-9]{3}$/';
		$tnexp[1] =  '/^02079460[0-9]{3}$/';
		$tnexp[2] =  '/^01914980[0-9]{3}$/';
		$tnexp[3] =  '/^02890180[0-9]{3}$/';
		$tnexp[4] =  '/^02920180[0-9]{3}$/';
		$tnexp[5] =  '/^01632960[0-9]{3}$/';
		$tnexp[6] =  '/^07700900[0-9]{3}$/';
		$tnexp[7] =  '/^08081570[0-9]{3}$/';
		$tnexp[8] =  '/^09098790[0-9]{3}$/';
		$tnexp[9] =  '/^03069990[0-9]{3}$/';
		
	  	foreach ($tnexp as $regexp) {  
			if (preg_match($regexp,$strTelephoneNumberCopy, $matches)) {
	      		$intError = 5;
	      		$strError = 'The telephone number is either invalid or inappropriate';
	      		return false;
	    	}
	  	}
	  
	  	// Finally, check that the telephone number is appropriate.
	  	if (!preg_match('/^(01|02|03|05|070|071|072|073|074|075|07624|077|078|079)[0-9]+$/',$strTelephoneNumberCopy)) {
	    	$intError = 5;
	    	$strError = 'The telephone number is either invalid or inappropriate';
	    	return false;
	  	}
	  
	  	if($stripped){
		  	// Seems to be valid - return the stripped telephone number
		  	$strTelephoneNumber = $strTelephoneNumberCopy;
	  	}
	  	$intError = 0;
	  	$strError = '';
	  	return true;  
	}
}
